var taskmodel = require('../../sys/tool/task')
Component({

  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {

    viewsize: {
      type: String,
      value: "80px"
    },
    uploadText: {
      type: String,
      value: ""   //single,more
    },

    imageFit: {
      type: String,
      value: "scaleToFill"   //single,more
    },
    customStyle: {
      type: String,
      value: ""
    },
    customitemStyle: {
      type: String,
      value: ""
    },
    max: {
      type: Number,
      value: 1
    },
    value: {
      type: Array,
      value: []
    },
    uploadIcon: {
      type: String,
      value: 'photograph',
    },
    mediaType:{
      type: String,
      value: 'image',
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    taskid: 1,
    task: {},
    viewstyle: ""

  },


  ready() { 
    if (this.data.viewsize) {
      var viewstyle = "width:" + this.data.viewsize + ";height:" + this.data.viewsize
      this.setData({ viewstyle })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {

    clearitem() {
      this.setData({ value: [] })
    },
    deleteItem: function (ev) {

      var idx = ev.currentTarget.dataset.index
      this._delitem(idx);

    },
    _delitem(idx) {
      var value = this.data.value
      if (value[idx].taskid) {
        taskmodel.del(fileList[idx].taskid)
      }
      value.splice(idx, 1)
      this.setData({ value })
      this.triggerEvent("change", value)
    },
    onClickPreview: function (ev) {

      var value = this.data.value
      wx.previewImage({
        current: '', // 当前显示图片的http链接
        urls: value // 需要预览的图片http链接列表
      })

    },
    showopmen(ev) {
      var dataset = ev.currentTarget.dataset
      var idx = dataset.index
      var value = this.data.value;
      var item = value[idx]
      var opcode = null;
      opcode = ['删除', '重传']
      if(this.data.mediaType=='image'){
        opcode.push('浏览')
      }else{
        opcode.push('播放')
      }

      if (!item.url) {
        if (idx != 0) {
          opcode.push("上移")
        }
        if ((value.length - 1) > idx) {
          opcode.push("下移")
        }
      };
      var that = this
      wx.showActionSheet({
        itemList: opcode,
        success(res) {
          switch (opcode[res.tapIndex]) {
            case "删除": {
              that._delitem(idx)
              break;
            }
            case "重传": {
              that._reupload(idx)
              break;
            }
            case "上移": {
              var index1 = idx
              var index2 = idx - 1;
              value[index1] = value.splice(index2, 1, value[index1])[0];
              that.setData({ value })

              that.triggerEvent("change", value)
              break;
            }
            case "下移": {
              var index1 = idx
              var index2 = idx + 1;
              value[index1] = value.splice(index2, 1, value[index1])[0];
              that.setData({ value })
              that.triggerEvent("change", value)
              break;
            }
            case "浏览": {
              var imgs = []
              value.forEach(item => {
                if (item.url) {
                  imgs.push(item.url)
                }
                else {
                  imgs.push(item);
                }

              })

              wx.previewImage({
                current: imgs['idx'], // 当前显示图片的http链接
                urls: imgs // 需要预览的图片http链接列表
              })
              break;
            }
            case "播放": {
              // console.log("播放")
              var name='video_'+idx
              // console.log(name)

              var videoplay = wx.createVideoContext(name, that)
              // videoplay.requestFullScreen()
              videoplay.requestFullScreen();

              videoplay.play()
              break;
            }

          }

        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    },
    
    _reupload: function (idx) {
      var that = this;
      var value = this.data.value

      wx.chooseMedia({
        count: 1,
        mediaType:this.data.mediaType,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          var url = res.tempFilePaths[0]
          var newmodel = { url: url, status: -1, taskid: taskmodel.create() };
          value.splice(idx, 1, newmodel)
          that.setData({ value })
          that.updatefile([newmodel]);
        }
      })
    },
    startUpload: function () {
      console.log("startUpload")

      var that = this;
      var max = this.data.max
      var value = this.data.value;
      var mediaType=[];
      mediaType.push(this.data.mediaType)
      // console.log("xxxxxxxxxxxxxxxxx")
      // console.log(mediaType)
      // console.log(max)
      // console.log(value.length)
      // wx.getSystemInfo({
      //   success: function (res) {
      //       let version = res.SDKVersion;
      //       version = version.replace(/\./g, "");
      //       console.log('当前版本号: '+version);
      //   }
      // });


      // 
      wx.chooseMedia({
        count: max - value.length > 9 ?9:max - value.length,
        mediaType:mediaType,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          console.log("res")
          console.log(res)

          // tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFiles
          var items = [];
          tempFilePaths.forEach(item => {
            var newmodel = { url: item.tempFilePath, status: -1, taskid: taskmodel.create() };
            items.push(newmodel)
          })
          value = value.concat(items)
          that.setData({ value })
          that.updatefile(items);
        },fail(res){
          console.log("fail")
          console.log(res)

        }
      })
    },
    updatefile(items) {
      var app = getApp();
      var that = this
      console.log("11111111111111111111111111111")

      items.forEach(function (temmodel) {
        app.toolv2.uploadFile(temmodel.url).then(function (item) {
          if (item.status == 1) {
            var value = that.data.value;
            var len = value.length;
            if (taskmodel.del(temmodel.taskid)) {
              for (var i = 0; i < len; i++) {
                if (value[i].taskid == temmodel.taskid) {
                  var updatemodel = {}
                  updatemodel["value[" + i + "]"] = item.obj.fullpath;
                  that.setData(updatemodel);
                  console.log("ddd")

                  console.log(that.data.value)

                  that.triggerEvent("change", that.data.value)
                  break;
                }
              }
            }
          }
        })
      })
    },
    fullscreenchange(e){
      // console.log("fullscreenchange")
      // console.log(e)
      var {fullScreen, direction}=e.detail;
      if(!fullScreen){
        var name=e.currentTarget.id
        var videoplay = wx.createVideoContext(name, this)
        videoplay.stop()
      }
    }

  }
})
